using System;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace MqttPublisher
{
    public partial class MainForm : Form
    {
        private MqttService _mqttService;

        public MainForm()
        {
            InitializeComponent();
            InitializeMqttService();
            InitializeUI();
        }

        private void InitializeMqttService()
        {
            _mqttService = new MqttService();
            _mqttService.OnStatusChanged += OnMqttStatusChanged;
            _mqttService.OnMessageSent += OnMqttMessageSent;
        }

        private void InitializeUI()
        {
            // 设置默认设备类型
            cmbDeviceType.SelectedIndex = 0;
            
            // 初始状态下禁用发布功能
            groupBoxPublish.Enabled = false;
        }

        private void OnMqttStatusChanged(object sender, string status)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, string>(OnMqttStatusChanged), sender, status);
                return;
            }

            toolStripStatusLabel1.Text = status;
            AppendLog($"[状态] {status}");
            
            // 更新按钮状态
            btnConnect.Enabled = !_mqttService.IsConnected;
            btnDisconnect.Enabled = _mqttService.IsConnected;
            groupBoxPublish.Enabled = _mqttService.IsConnected;
        }

        private void OnMqttMessageSent(object sender, string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, string>(OnMqttMessageSent), sender, message);
                return;
            }

            AppendLog($"[发送] {message}");
        }

        private void AppendLog(string message)
        {
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            txtLog.AppendText($"[{timestamp}] {message}\r\n");
            txtLog.ScrollToCaret();
        }    
    private async void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = false;
            
            try
            {
                string brokerIp = txtBrokerIp.Text.Trim();
                string username = txtUsername.Text.Trim();
                string password = txtPassword.Text.Trim();
                
                if (!int.TryParse(txtPort.Text.Trim(), out int port))
                {
                    MessageBox.Show("端口号格式不正确！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                AppendLog($"正在连接到深圳MQTT服务器 {brokerIp}:{port}...");
                bool connected = await _mqttService.ConnectAsync(brokerIp, port, username, password);
                
                if (!connected)
                {
                    btnConnect.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnConnect.Enabled = true;
            }
        }

        private async void btnDisconnect_Click(object sender, EventArgs e)
        {
            btnDisconnect.Enabled = false;
            
            try
            {
                await _mqttService.DisconnectAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"断开连接异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnDisconnect.Enabled = true;
            }
        }

        private async void btnSendEquipment_Click(object sender, EventArgs e)
        {
            if (!_mqttService.IsConnected)
            {
                MessageBox.Show("请先连接到MQTT Broker！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // 验证输入
                if (cmbDeviceType.SelectedItem == null)
                {
                    MessageBox.Show("请选择设备类型！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrEmpty(txtDeviceCode.Text.Trim()))
                {
                    MessageBox.Show("资产编号不能为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrEmpty(txtEquipmentName.Text.Trim()))
                {
                    MessageBox.Show("设备名称不能为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 创建设备状态数据
                var equipmentData = new EquipmentStateRequest
                {
                    messageName = "eqpStateRequest",
                    deviceCode = txtDeviceCode.Text.Trim(),
                    equipmentName = txtEquipmentName.Text.Trim(),
                    transactionID = MqttService.GenerateTransactionId(),
                    timeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                    parameters = new EquipmentParameters
                    {
                        onlineState = (int)numOnlineState.Value,
                        deviceStatus = (int)numDeviceStatus.Value,
                        deviceStatusType = (int)numDeviceStatusType.Value,
                        safeState = (int)numSafeState.Value,
                        colorLightState = (int)numColorLightState.Value,
                        operationMode = (int)numOperationMode.Value
                    }
                };

                // 构建Topic
                DeviceType deviceType = (DeviceType)Enum.Parse(typeof(DeviceType), cmbDeviceType.SelectedItem.ToString());
                string topic = MqttService.BuildDeviceTopic(deviceType);

                btnSendEquipment.Enabled = false;
                bool success = await _mqttService.PublishJsonAsync(topic, equipmentData);
                
                if (success)
                {
                    AppendLog($"设备状态数据发送成功到主题: {topic}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发送异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                AppendLog($"发送异常: {ex.Message}");
            }
            finally
            {
                btnSendEquipment.Enabled = true;
            }
        }

        private async void btnSendCustom_Click(object sender, EventArgs e)
        {
            if (!_mqttService.IsConnected)
            {
                MessageBox.Show("请先连接到MQTT Broker！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                string customJson = txtCustomJson.Text.Trim();
                if (string.IsNullOrEmpty(customJson))
                {
                    MessageBox.Show("自定义JSON不能为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 验证JSON格式
                try
                {
                    var jsonObject = JsonConvert.DeserializeObject(customJson);
                }
                catch (JsonException)
                {
                    MessageBox.Show("JSON格式不正确！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 验证设备类型选择
                if (cmbDeviceType.SelectedItem == null)
                {
                    MessageBox.Show("请选择设备类型！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 构建Topic
                DeviceType deviceType = (DeviceType)Enum.Parse(typeof(DeviceType), cmbDeviceType.SelectedItem.ToString());
                string topic = MqttService.BuildDeviceTopic(deviceType);

                btnSendCustom.Enabled = false;
                
                // 直接发送JSON字符串
                var message = new MQTTnet.MqttApplicationMessageBuilder()
                    .WithTopic(topic)
                    .WithPayload(customJson)
                    .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
                    .WithRetainFlag(false)
                    .Build();

                var result = await _mqttService.MqttClient.PublishAsync(message);
                
                if (result.IsSuccess)
                {
                    AppendLog($"自定义JSON发送成功到主题 '{topic}': {customJson}");
                }
                else
                {
                    AppendLog($"发送失败: {result.ReasonString}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发送异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                AppendLog($"发送异常: {ex.Message}");
            }
            finally
            {
                btnSendCustom.Enabled = true;
            }
        }

        private void btnClearLog_Click(object sender, EventArgs e)
        {
            txtLog.Clear();
        }

        private async void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_mqttService != null && _mqttService.IsConnected)
            {
                await _mqttService.DisconnectAsync();
                _mqttService.Dispose();
            }
        }
    }
}